<?php

namespace App\Controller\App;

use App\Base\BaseCache;
use App\Base\BaseController4App;
use App\Base\Format;
use App\Entity\User;
use App\Model\LazyCommon\MiniAppModel;
use App\Model\LazyCommon\UserModel;
use App\Model\TopicModel;
use App\Model\UserLiveModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;

/**
 * @route("/app")
 */
class UserController extends BaseController4App
{


    /**
     * @route("/wechat_login",name="getWechetLogin")
     */
    public function getMniAppInitData()
    {
        if(!$code = $this->getParamRequired("code")){return $this->json_out(0,"Code is missed");}
        $MiniAppModel = new MiniAppModel($this->getDoctrine());
        $rst = $MiniAppModel->getOpenidAndAccessToken4Mini($code);
        //$rst = "oHSdp5FwwtlspPaPqcxCg5yPU9yc";
        if ($rst) {
            //检查用户是否存在如果存在就登录ID，不存在就创建用户
            $UserModel = new UserModel($this->getDoctrine());
            $user = $UserModel->getByWeChetId($MiniAppModel->Openid);
            $sessionData = $UserModel->createSessionData($user);
            $user->setLastLoginTime(time());
            $this->myEm()->persist($user);
            $this->myEm()->flush();
            //启用Cache
            $BaseCache = new BaseCache();
            $access_token = $BaseCache->getUserAccessToken(Request::createFromGlobals());;
            $BaseCache->createUserToken($access_token,$sessionData);
            return $this->json_out(1,"登陆成功",$this->data);
        } else {
            return $this->json_out(0,"系统异常",$this->data);
        }
    }

    /**
     * @route("/send_sms",name="AppSendSms")
     */
    public function AppSendSms()
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(0,"请输入手机号");}
        $is = new Format();
        if (!$is->isPhone($phone)) {
            return $this->json_out(0,"手机号错误");
        }

        $lastTime = $this->mySession()->get("smsLastTime");
        if ($lastTime > time() - 18) {
            return $this->json_out(0,"操作太频繁");
        }
        $smsRecentCount = $this->mySession()->get("smsRecentCount");
        $smsRecentDate = $this->mySession()->get("smsRecentDate");
        if (!$smsRecentCount || $smsRecentDate != date("Ymd") ) {
            $smsRecentCount = 1;
        }else{
            $smsRecentCount++;
        }
        if ($smsRecentCount > 50) {
            return $this->json_out(0,"尝试次数超出上限");
        }

        require_once __DIR__."/../../../BaseExt/Sms.php";
        $sms = new \Sms();
        $rand = rand(1000,9999);
//        $sms->sendSms($phone,"SMS_174166578",array("code"=>$rand));
        $this->mySession()->set("smsCode",$rand);
        $this->mySession()->set("smsLastTime",time());
        $this->mySession()->set("smsLastPhone",$phone);
        $this->mySession()->set("smsRecentCount",$smsRecentCount);
        $this->mySession()->set("smsRecentDate",date("Ymd"));
        return $this->json_out(1,"已发送 $rand");
    }




    /**
     * @route("/login_sms",name="AppUserSMSLogin")
     */
    public function AppUserSMSLogin(Request $request)
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(0,"请输入手机号");}
        $is = new Format();
        if (!$is->isPhone($phone)) {return $this->json_out(0,"手机号错误");}
        $smsLastPhone = $this->mySession()->get("smsLastPhone");
        if ($smsLastPhone != $phone) {return $this->json_out(0,"手机号不一致");}
        $smsCode = $this->mySession()->get("smsCode");
        if (!$code = $this->getParamRequired("code")) {return $this->json_out(0,"请输入验证码");}
        if ($code != $smsCode) {return $this->json_out(0,"验证码错误");}

        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getByPhone($phone);
        if (!$user) {
            $user = new User();
            $user->setParent(0)
                ->setAddTime(time())
                ->setPhone($phone)
                ->setGroups(3)
                ->setAccount($phone)
                ->setNickName("聪明学用户")
                ->setHeadPic("/assets/images/user.png")
                ->setPassword(md5($phone))->setPasswordPay(md5($phone));
            $this->myEm()->persist($user);
            $this->myEm()->flush();
        }
        if ($user->getBan() == 1) {
            return $this->json_out(0,"访问受限");
        }
        $user->setLastLoginTime(time())
            ->setLastLoginIp($request->getClientIp())
            ->setPasswordPay($request->headers->get("sessId"));
        $this->myEm()->persist($user);
        $this->myEm()->flush();
//        var_dump($user->getRoles());
        //设置缓存
        $sessionData = $UserModel->createSessionData($user);
//        $this->mySession()->set()
        //启用Cache
        $BaseCache = new BaseCache();
        $access_token = $BaseCache->getUserAccessToken($request);;
        $BaseCache->createUserToken($access_token,$sessionData);

        return $this->json_out(1,"登录成功",$sessionData);
    }



    /**
     * @route("/user/info",name="AppUserInfo")
     */
    public function AppUserInfo(Request $request)
    {
        $uid = $this->needToBeUser();

        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        if ($request->getMethod() == "POST") {
            if ($nickName = $this->getParamRequired("nickName")) {
                $user->setNickName($nickName);
            }
            if ($headPic = $this->getParamRequired("headPic")) {
                $user->setHeadPic($headPic);
            }
            if ($grade = $this->getParamRequired("grade")) {
                $user->setQq($grade);
            }
            $this->myEm()->persist($user);$this->myEm()->flush();
        }
        $this->data["user"] = $UserModel->getBaseInfo($user);
        return $this->json_out(1,"OK",$this->data);

    }

    /**
     * @route("/user/home",name="AppUserHome")
     */
    public function AppUserHome()
    {
        if (!$uid = $this->isUser()) {

            $data["user"]["id"] = 0;
            $data["user"]["nickName"] = "聪明学用户";
            $data["user"]["headPic"] = "/assets/images/user.png";
            $data["user"]["grade"] = "2";
            $data["user"]["isVip"] = "0";
            $data["user"]["live"] = [];

            return $this->json_out(1,"尚未登录",$data);
        }else{
            $UserModel = new UserModel($this->getDoctrine());
            $user = $UserModel->getUserById($uid);
            if ($user->getBan() == 1 ) {
                return $this->json_out(203,"访问受限");
            }

            $term = $user->getWechat();
            $isVip = 0;
            if ($term > time()) {
                $isVip = 1;
            }

            $this->data["user"] = $UserModel->getBaseInfo($user);
            $this->data["user"]["isVip"] = $isVip;
            //我的课程
            $UserLiveModel = new UserLiveModel($this->getDoctrine());
            $liveList = $UserLiveModel->getUserLive($uid);
            foreach ($liveList as &$row) {
                $row["content"] = "";
                $time = $this->getDayStart() + $row["time_int"];
                $row["datetime"] = date("Y 年 m 月 d 日 H:i",$time);
                $row["near"] = 0;
                if ($time > time() && $time  < time() + 60 * 30 ) {
                    $row["near"] = 1;
                }
            }
            $this->data["live"] = $liveList;

            return $this->json_out(1,"OK",$this->data);
        }
    }

    /**
     * @route("/user/card",name="AppUserVipCard")
     */
    public function AppUserVipCard()
    {
        $uid = $this->needToBeUser();
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);

        $time = $user->getWechat();
        $this->data["date"] = date("Y 年 m 月 d 日",$time);
        $month = floor(($time - time())/(30*24*3600));
        $this->data["month"] = $month;
        $this->data["error"] = 0;
        if ($time < time()) {
            $this->data["error"] = 1;
        }
        return $this->json_out(1,"OK",$this->data);



    }


}
